//
//  MessageVC.m
//  WanCaiC8
//
//  Created by tangang on 2018/1/19.
//  Copyright © 2018年 tangang. All rights reserved.
//

#import "MessageVC.h"
#import "MessageCommentsCell.h"
#import "MessageCell.h"
#import "MJRefresh.h"
#import "MyVM.h"
#import "MessageCell.h"
#import "CommentsTextView.h"
#import "PlanVM.h"
@interface MessageVC ()<UITableViewDelegate,UITableViewDataSource,UINavigationControllerDelegate, UIImagePickerControllerDelegate>
@property (nonatomic ,strong) UITableView *tableView;
@property (nonatomic ,strong) NSMutableArray *dataArr;
@property (nonatomic ,strong) CommentsTextView *cTextView;
@property (nonatomic ,strong) NSMutableArray  *commentsImages;
@end

@implementation MessageVC{
    RITLPhotoNavigationViewModel * viewModel;
    UIButton    *btnComment;
    UIButton    *btnSystem;
    QXLable     *labSystemCount;
    UIView      *lineView;
    NSInteger   type;
    NSInteger   page;
    NSString    *sendStr;
    CommentModel    *selectModel;
    
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title=@"消息提醒";
    viewModel = [RITLPhotoNavigationViewModel new];
    [self headView];
    [self.tableView.header beginRefreshing];
    
    [[MyVM manage] getNoticeNoReadWithSuccess:^(id returnValue) {
        NSInteger count=[[returnValue objectForKey:@"SysMessageCount"] integerValue];
        if (count>0) {
            labSystemCount.hidden=NO;
            labSystemCount.text=[NSString stringWithFormat:@"%ld",count];
        }
    } andFail:^(NSString *errorMessage, NSError *error) {
        
    }];
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
}

- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillHideNotification object:nil];
}

- (void)headView{
    WS(weakSelf);
    UIView *topView=[[UIView alloc]init];
    topView.backgroundColor=[UIColor whiteColor];
    [self.view addSubview:topView];
    [topView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.top.equalTo(weakSelf.view);
        make.height.mas_equalTo(@(real_size(44)));
    }];
    
    btnComment=[self createBtnWithTitle:@"评论"];
    btnComment.tag=0;
    [topView addSubview:btnComment];
    [btnComment mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.top.bottom.equalTo(topView);
        make.width.equalTo(topView).with.multipliedBy(1/2.0);
    }];
    
    btnSystem=[self createBtnWithTitle:@"系统消息"];
    btnSystem.tag=1;
    [topView addSubview:btnSystem];
    [btnSystem mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.bottom.equalTo(topView);
        make.right.equalTo(topView);
        make.width.equalTo(topView).with.multipliedBy(1/2.0);
    }];
    
    labSystemCount=[[QXLable alloc]initWithFount:9];
    labSystemCount.backgroundColor=NAVCOLOR;
    labSystemCount.text=@"0";
    labSystemCount.hidden=YES;
    labSystemCount.layer.masksToBounds=YES;
    labSystemCount.layer.cornerRadius=real_size(10);
    labSystemCount.textAlignment=NSTextAlignmentCenter;
    labSystemCount.textColor=[UIColor whiteColor];
    [topView addSubview:labSystemCount];
    [labSystemCount mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(btnSystem).with.offset(35);
        make.centerY.equalTo(btnSystem).with.offset(-8);
        make.size.mas_equalTo(CGSizeMake(real_size(20), real_size(20)));
    }];
    
    lineView=[[UIView alloc]init];
    lineView.backgroundColor=NAVCOLOR;
    [topView addSubview:lineView];
    [lineView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(btnComment);
        make.bottom.equalTo(topView);
        make.size.mas_equalTo(CGSizeMake(44, 2));
    }];
}

- (UIButton *)createBtnWithTitle:(NSString *)title{
    UIButton *btn=[[UIButton alloc]init];
    [btn addTarget:self action:@selector(onclickTop:) forControlEvents:UIControlEventTouchUpInside];
    [btn setTitle:title forState:UIControlStateNormal];
    [btn setTitleColor:DEFAULTTEXTGDARKRAYCOLOR forState:UIControlStateNormal];
    [btn.titleLabel setFont:[UIFont systemFontOfSize:15]];
    return btn;
}


- (void)onclickTop:(UIButton *)sender{
    type=sender.tag;
    [self.tableView.header beginRefreshing];
    if (sender.tag==0) {
        [lineView mas_updateConstraints:^(MASConstraintMaker *make) {
            make.centerX.equalTo(sender);
        }];
    }else if (sender.tag==1){
        [lineView mas_updateConstraints:^(MASConstraintMaker *make) {
            make.centerX.equalTo(btnComment).with.offset(SCREEN_WIDTH/2.0);
        }];
    }
}

#pragma mark -- 获取评论消息
- (void)getCommentMessage{
    WS(weakSelf);
    [[MyVM manage] getCommentNoticeWithPage:page andSuccess:^(id returnValue) {
        NSArray *arr=returnValue;
        if (arr.count<[defaultPageSize integerValue]) {
            [weakSelf.tableView.footer noticeNoMoreData];
        }else{
            [weakSelf.tableView.footer endRefreshing];
        }
        [weakSelf.dataArr addObjectsFromArray:arr];
        page+=1;
        [weakSelf.tableView.header endRefreshing];
        [weakSelf.tableView reloadData];
    } andFail:^(NSString *errorMessage, NSError *error) {
        [weakSelf.tableView.header endRefreshing];
        [weakSelf.tableView.footer endRefreshing];
    }];
}

#pragma mark -- 获取系统消息
- (void)getSystemMessage{
    WS(weakSelf);
    [[MyVM manage] getSystemNoticeWithPage:page andSuccess:^(id returnValue) {
        NSArray *arr=returnValue;
        if (arr.count<[defaultPageSize integerValue]) {
            [weakSelf.tableView.footer noticeNoMoreData];
        }else{
            [weakSelf.tableView.footer endRefreshing];
        }
        [weakSelf.dataArr addObjectsFromArray:arr];
        page+=1;
        [weakSelf.tableView.header endRefreshing];
        [weakSelf.tableView reloadData];
    } andFail:^(NSString *errorMessage, NSError *error) {
        [weakSelf.tableView.header endRefreshing];
        [weakSelf.tableView.footer endRefreshing];
    }];
}


#pragma mark -- 选择照片
- (void)selectPic{
    
    if (self.commentsImages.count>2) {
        [SVProgressHUD showErrorWithStatus:@"最多只能上传3张图片"];
        return;
    }
    
    sendStr=self.cTextView.textView.text;
    [self.cTextView removeSelf];
    UIAlertController *alertCtrl=[UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    UIAlertAction *cancleAction=[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];;
    UIAlertAction *albumAction=[UIAlertAction actionWithTitle:@"从手机相册选择" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        WS(weakSelf);
        viewModel.RITLBridgeGetImageBlock = ^(NSArray  * images){
            for (NSDictionary *dict in images) {
                [weakSelf.commentsImages addObject:[dict objectForKey:@"image"]];
            }
            [weakSelf.cTextView.textView becomeFirstResponder];
        };
        self.hidesBottomBarWhenPushed = NO;
        viewModel.maxNumberOfSelectedPhoto=3-self.commentsImages.count;
        RITLPhotoNavigationViewController * viewController = [RITLPhotoNavigationViewController photosViewModelInstance:viewModel];
        [self presentViewController:viewController animated:true completion:^{}];
    }];
    UIAlertAction *cameraAction=[UIAlertAction actionWithTitle:@"拍照" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        UIImagePickerControllerSourceType sourceType = UIImagePickerControllerSourceTypeCamera;
        UIImagePickerController * ipc = [[UIImagePickerController alloc] init];
        ipc.delegate = self;
        ipc.sourceType = sourceType;
        [self presentViewController:ipc animated:YES completion:nil];
    }];
    [alertCtrl addAction:cancleAction];
    [alertCtrl addAction:albumAction];
    [alertCtrl addAction:cameraAction];
    [self presentViewController:alertCtrl animated:YES completion:nil];
}


#pragma mark -- 发布评论
- (void)publishComment{
    WS(weakSelf);
    [SVProgressHUD show];
    [self postImageWithDoneArr:[NSMutableArray new] done:^(NSMutableArray *arr) {
        [[PlanVM manage] publishWithId:selectModel.RefId andType:selectModel.CommentType andContent:[[SocketRocketUtility instance] sendMessageConversion:self.cTextView.textView.text] andCommentType:2 andUserId:selectModel.FromUserId andPic:arr Success:^(id returnValue) {
            [self.commentsImages removeAllObjects];
            sendStr=nil;
            selectModel=nil;
            [weakSelf.cTextView removeSelf];
            [SVProgressHUD showSuccessWithStatus:@"回复成功"];
        } andFail:^(NSString *errorMessage, NSError *error) {
            
        }];
    }];
    
}

- (void)postImageWithDoneArr:(NSMutableArray *)doneArr done:(void(^)(NSMutableArray *arr))doneBlock{
    if (doneArr.count==self.commentsImages.count) {
        doneBlock(doneArr);
        return;
    }
    WS(weakSelf);
    [[BaseVM manage] postImageWithImage:self.commentsImages[doneArr.count] andType:3 andSuccess:^(id returnValue) {
        [doneArr addObject:[returnValue objectForKey:@"ResouceId"]];
        [weakSelf postImageWithDoneArr:doneArr done:doneBlock];
    } andFail:^(NSString *errorMessage, NSError *error) {
        
    }];
}
#pragma mark - tableView输入框遮挡
- (void)keyboardWillShow:(NSNotification *)notification {
    NSDictionary *userInfo = [notification userInfo];
    NSValue* aValue = [userInfo objectForKey:UIKeyboardFrameEndUserInfoKey];
    CGRect keyboardRect = [aValue CGRectValue];
    keyboardRect = [self.view convertRect:keyboardRect fromView:nil];
    CGFloat keyboardTop = keyboardRect.origin.y;
    NSValue *animationDurationValue = [userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey];
    NSTimeInterval animationDuration;
    [animationDurationValue getValue:&animationDuration];
    [UIView beginAnimations:nil context:NULL];
    [UIView setAnimationDuration:animationDuration];
    [self.cTextView mas_updateConstraints:^(MASConstraintMaker *make) {
        make.height.mas_equalTo(@(keyboardTop+(SCREEN_WIDTH-60)/6+10+HEIGHT_CHATBOXVIEW-(self.cTextView.imageArr.count>0?(SCREEN_WIDTH-60)/6+5:0)));
    }];
    [UIView commitAnimations];
}

- (void)keyboardWillHide:(NSNotification *)notification {
    NSDictionary* userInfo = [notification userInfo];
    NSValue *animationDurationValue = [userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey];
    NSTimeInterval animationDuration;
    [animationDurationValue getValue:&animationDuration];
    [UIView beginAnimations:nil context:NULL];
    [UIView setAnimationDuration:animationDuration];
    [self.cTextView mas_updateConstraints:^(MASConstraintMaker *make) {
        make.height.mas_equalTo(@(SCREEN_HEIGHT+(self.cTextView.imageArr.count>0?(SCREEN_WIDTH-60)/6:0)));
    }];
    [UIView commitAnimations];
    
}

#pragma mark -- UITableViewDelegate ,UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.dataArr.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 5;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    UIView *view=[[UIView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 10)];
    view.backgroundColor=DEFAULTBGCOLOR;
    return view;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (type==0) {
        MessageCommentsCell *cell=[tableView dequeueReusableCellWithIdentifier:@"MessageCommentsCell" forIndexPath:indexPath];
        cell.model=self.dataArr[indexPath.row];
        WS(weakSelf);
        cell.replyBlock = ^(CommentModel *model) {
            selectModel=model;
            [weakSelf.cTextView.textView becomeFirstResponder];
        };
        return cell;
    }else{
        MessageCell *cell=[tableView dequeueReusableCellWithIdentifier:@"MessageCell" forIndexPath:indexPath];
        cell.model=self.dataArr[indexPath.row];
        return cell;
    }
    
}

#pragma mark -- UINavigationControllerDelegate, UIImagePickerControllerDelegate
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    UIImage *image = [info objectForKey:UIImagePickerControllerOriginalImage];
    if (!self.commentsImages) {
        self.commentsImages=[[NSMutableArray alloc]init];
    }
    [self.commentsImages addObject:image];
    [self dismissViewControllerAnimated:YES completion:^{
        [self.cTextView.textView becomeFirstResponder];
    }];
    
    
}


#pragma mark -- 懒加载
- (UITableView *)tableView{
    if (!_tableView) {
        WS(weakSelf);
        _tableView=[[UITableView alloc]init];
        _tableView.dataSource=self;
        _tableView.delegate=self;
        _tableView.backgroundColor=DEFAULTBGCOLOR;
        [_tableView registerClass:[MessageCommentsCell class] forCellReuseIdentifier:@"MessageCommentsCell"];
        [_tableView registerClass:[MessageCell class] forCellReuseIdentifier:@"MessageCell"];
        _tableView.separatorStyle=UITableViewCellSeparatorStyleNone;
        _tableView.header=[MJRefreshNormalHeader headerWithRefreshingBlock:^{
            page=1;
            [weakSelf.dataArr removeAllObjects];
            [weakSelf.tableView reloadData];
            if (type==0) {
                [weakSelf getCommentMessage];
            }else{
                labSystemCount.hidden=YES;
                [weakSelf getSystemMessage];
            }
        }];
        _tableView.footer=[MJRefreshBackNormalFooter footerWithRefreshingBlock:^{
            if (type==0) {
                [weakSelf getCommentMessage];
            }else{
                [weakSelf getSystemMessage];
            }
        }];
        _tableView.rowHeight=UITableViewAutomaticDimension;
        _tableView.estimatedRowHeight=100;
        [self.view addSubview:_tableView];
        [_tableView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.edges.equalTo(weakSelf.view).with.
            insets(UIEdgeInsetsMake((real_size(44)), 0, 0, 0));
        }];
    }
    return _tableView;
}

- (NSMutableArray *)dataArr{
    if (!_dataArr) {
        _dataArr=[[NSMutableArray alloc]init];
    }
    return _dataArr;
}

- (CommentsTextView *)cTextView{
    if (!_cTextView) {
        WS(weakSelf);
        _cTextView=[[CommentsTextView alloc]init];
        _cTextView.textView.text=sendStr;
        [_cTextView setImageArr:self.commentsImages];
        _cTextView.clickEmj = ^(BOOL isFace) {
            if (isFace) {
                [weakSelf.cTextView.textView resignFirstResponder];
                [weakSelf.cTextView mas_updateConstraints:^(MASConstraintMaker *make) {
                    make.height.mas_equalTo(@(SCREEN_HEIGHT+(self.cTextView.imageArr.count>0?(SCREEN_WIDTH-60)/6:0)));
                }];
            }else{
                [weakSelf.cTextView.textView becomeFirstResponder];
            }
        };
        _cTextView.showPic = ^ {
            [weakSelf selectPic];
        };
        
        _cTextView.sendBlock = ^{
            [weakSelf publishComment];
            
        };
        _cTextView.removeBlock = ^{
            [weakSelf.cTextView removeFromSuperview];
            weakSelf.cTextView=nil;
        };
        [self.view addSubview:_cTextView];
        [_cTextView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.right.top.equalTo(self.view);
            make.height.mas_equalTo(@0);
        }];
    }
    return _cTextView;
}

- (NSMutableArray *)commentsImages{
    if (!_commentsImages) {
        _commentsImages=[[NSMutableArray alloc]init];
    }
    return _commentsImages;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
